//记录查询出的所有用户信息
var areaMoblieobj=new Array();
//记录点击当前行的ID 修改信息使用
var areaMoblieId;

Ext.onReady(function(){
	
	areaMoblieiswriteidb= Ext.get('areaMoblieiswriteid').getValue()==1?true:false;
	
	var areaMoblieNameField=new Ext.form.NumberField({
		fieldLabel:'手机号段',
		labelAlign:'right'
	});
	
	var areaMoblieProvinceName=new Ext.form.ComboBox({
		fieldLabel:'省 份',
		labelAlign:'right',
		width:80,
		autoScroll:true,
		store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsProvince.do',
            fields:['nAreaId','sName','sCode']
//            listeners:{
//           		load : function(stor,record,opts){
//           			areaMoblieProvinceName.setValue(record[0].data.nAreaId);
//           			areaMoblieCityName.clearValue();
//		           	areaMoblieCityName.getStore().load({
//		           		params:{nProvinceId:areaMoblieProvinceName.getValue()}
//		           	});
//           		}
//           	}
        }),
        hiddenValue:'sCode',
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
//        selectOnFocus:true,
//        editable:false,
        emptyText:'全 部',
        listeners:{
           select : function(combo, record,index)  {
            areaMoblieCityName.clearValue();
//            alert(areaMoblieProvinceName.getValue());
           	areaMoblieCityName.getStore().load({
           		params:{nProvinceId:areaMoblieProvinceName.getValue()}
           	});
          }
       }
	});
	
	var areaMoblieCityName=new Ext.form.ComboBox({
		fieldLabel:'城 市',
		labelAlign:'right',
		width:80,
		autoScroll:true,
        store: new Ext.data.JsonStore({
        	autoLoad:false,
            url:'selectsCitybyProvince.do',
            fields:['nAreaId','sName']
        }),
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'全 部',
        selectOnFocus:true,
        editable:false
	});
	
	var areaMoblienOPField=new Ext.form.ComboBox({
		width:80,
		fieldLabel: '运营商',
	    store: new Ext.data.ArrayStore({
	        fields:['value','text'],
	        data:[
	         		[0, '全部'],
			        [1, '移动'],
			        [2, '联通'],
			        [3,'电信']
		        ]
	    }),
	    mode:'local',
	    valueField:'value',
	    displayField:'text',
	    value:0,
	    editable:false,
	    triggerAction: 'all'
	});
	
	var areaMoblieSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			areaMoblieGridStore.load({
				params : {
					start : 0,
					limit : 20,
					'sName':areaMoblieNameField.getValue()
				}
			});
		}
	});
	
	var areaMoblieSearch=new Ext.Panel({
		height:70,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaMoblieProvinceName,areaMoblienOPField]},
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaMoblieCityName]},
			{columnWidth:.27,layout:'form',labelAlign:'right',items:[areaMoblieNameField]},
			{columnWidth:.15,layout:'form',labelAlign:'right',items:[areaMoblieSearchBtn]}]		
	});
	
	 areaMoblieAddBtn =new Ext.Button({
		text:'添加手机号段',
		hidden:areaMoblieiswriteidb,
		handler:function(){
			showareaMoblieAddForm(1);
		}
	});
	
	 areaMoblieGridStore = new Ext.data.Store({
        autoLoad: false,
        proxy : new Ext.data.HttpProxy({
            url: 'searchAreaMoblie.do'
        }),
        baseParams:{sName: areaMoblieNameField.getValue()},
        reader:new Ext.data.JsonReader({
             totalProperty: 'totalSize',
             root:'list'
        },[
            {name: 'nmobileRelAreaId',mapping:'nmobileRelAreaId', type: 'int'},
        	{name: 'smoblieNo',mapping:'smoblieNo', type: 'string'},
        	{name: 'sprovinceName',mapping:'sprovinceName', type: 'string'},
        	{name: 'scityName',mapping:'scityName', type: 'string'},
        	{name: 'nop',mapping:'nop', type: 'int'}
        ])
    });
    areaMoblieGridStore.on("beforeload", function(thiz, options) {
		thiz.baseParams["sName"] = areaMoblieNameField.getValue(); 
		thiz.baseParams["nprovinceId"] = areaMoblieProvinceName.getValue();
		thiz.baseParams["ncityId"] = areaMoblieCityName.getValue();
		thiz.baseParams["nop"] = areaMoblienOPField.getValue();
	});
    
	var areaMoblieGridBar=new Ext.PagingToolbar({
		store: areaMoblieGridStore,
		displayInfo: true,
		pageSize:20,
		displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		emptyMsg: "没有记录可以显示",
		beforePageText:'当前页码',
		afterPageText:'共{0}页', 
		firstText:'第一页', 
		prevText:'上一页', 
		nextText:'下一页', 
		lastText:'最后一页', 
		refreshText:'刷新当前页',
		items:['-', areaMoblieAddBtn]
     });
     
	areaMoblieGrid = new Ext.grid.GridPanel({
        store: areaMoblieGridStore,
        region:'center',
        bodyBorder:false,
        stripeRows:true,
		disableSelection: true,
		border:false,
		frame:true,
		loadMask :{msg:"数据加载中，请稍等..."},
		layout:'fit',
		viewConfig:{
			forceFit: true,
			scrollOffset:0
		},
        cm:new Ext.grid.ColumnModel([
        	new Ext.grid.RowNumberer(),
            {header: "标识", width:50, dataIndex: 'nmobileRelAreaId', sortable: true},
            {header: "手机号段", flex: 1, dataIndex: 'smoblieNo', sortable: true},
            {header: "省份",width:50, dataIndex: 'sprovinceName', sortable: true},
            {header: "城市",width:50, dataIndex: 'scityName', sortable: true},
            {header: "运营商", width:50, dataIndex: 'nop', sortable: true,
            	renderer:function(value){
            		if (value == 1) {
			            return '移动';
			        }else if(value == 2){
			        	return '联通';
			        }else if(value == 3){
			        	return '电信';
			        }
            	}
            },
            {header: "操作", width:150,align:'center',sortable: true,
            	renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
			    	var areaMoblieGridCrHtml='';
			    	areaMoblieobj[record.data.nmobileRelAreaId]=record.json;
			    	if(areaMoblieiswriteidb==false){
			    		areaMoblieGridCrHtml='<a onclick="areaMoblieGridColumnsRenderUplink('+record.data.nmobileRelAreaId+')" href="javascript:void(0)">修改</a>';
						areaMoblieGridCrHtml+='<a style="margin-left:20px;margin-right:20px" onclick="roleGridColumnsRenderDellink('+record.data.nmobileRelAreaId+')" href="javascript:void(0)">删除</a>';	
			    	}
					return areaMoblieGridCrHtml;
				}
            }
        ]),
        bbar: areaMoblieGridBar
    });
    
    
	 var areaMoblieMainPanel =new Ext.Viewport({
		layout:'border',
		renderTo:'areaMoblieDIV',
		id:'areaMoblieMainPanel',
		items:[areaMoblieGrid,areaMoblieSearch],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("areaMoblieMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
});
	var areaMoblieAddWin;
	var areaMoblieAddNameField=new Ext.form.NumberField({
		allowBlank:false,
		fieldLabel: '手机号段'
	});
	
	var areaMoblieAddProvinceName=new Ext.form.ComboBox({
		fieldLabel:'省 份',
		labelAlign:'right',
		width:80,
		autoScroll:true,
		store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsProvince.do',
            fields:['nAreaId','sName','sCode'],
            listeners:{
           		load : function(stor,record,opts){
           			areaMoblieAddProvinceName.setValue(record[0].data.nAreaId);
           			areaMoblieAddCityName.clearValue();
		           	areaMoblieAddCityName.getStore().load({
		           		params:{nProvinceId:areaMoblieAddProvinceName.getValue()}
		           	});
           		}
           	}
        }),
        hiddenValue:'sCode',
	    valueField:'nAreaId',
	    displayField:'sName',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
//        selectOnFocus:true,
        editable:false,
        listeners:{
           select : function(combo, record,index)  {     
            areaMoblieAddCityName.clearValue();
           	areaMoblieAddCityName.getStore().load({
           		params:{nProvinceId:areaMoblieAddProvinceName.getValue()}
           	});
          }
       }
	});
	
	var areaMoblieAddCityName=new Ext.form.ComboBox({
		fieldLabel:'城 市',
		labelAlign:'right',
		width:80,
		autoScroll:true,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectsCitybyProvince.do',
            fields:['nAreaId','sName','sCode']
        }),
	    valueField:'nAreaId',
	    displayField:'sName',
	    hiddenValue:'sCode',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        emptyText:'全 部',
        selectOnFocus:true,
        editable:false
	});
	
	var areaMoblieAddnOPField=new Ext.form.ComboBox({
		width:80,
		fieldLabel: '运营商',
	    store: new Ext.data.ArrayStore({
	        fields:['value','text'],
	        data:[
			        [1, '移动'],
			        [2, '联通'],
			        [3,'电信']
		        ]
	    }),
	    mode:'local',
	    valueField:'value',
	    displayField:'text',
	    value:1,
	    editable:false,
	    triggerAction: 'all'
	});
	
	//tinfo参数值1 :添加 2:修改
	function showareaMoblieAddForm(tinfo,areaMoblieJson) {
        if (!areaMoblieAddWin) {
            areaMoblieAddform = new Ext.FormPanel({
                border: false,
                labelAlign:'right',
                frame:true,
                items: [
                	areaMoblieAddProvinceName,areaMoblieAddCityName,
                	areaMoblieAddnOPField,areaMoblieAddNameField
                ],
                buttons: [{
                    text: '确 认',
                    handler: function() {
                    	
                    	if(!areaMoblieAddNameField.validate()){
                    		return ;
                    	}
                    	if(this.text=='添 加'){
                    		
                    		if(areaMoblieAddProvinceName.getRawValue()=='默认'){
                    			Ext.Msg.alert("信息!","请选择省份"); 
		                		return ;
                    		}
                    		
                    		if(areaMoblieAddCityName.getValue()==''||areaMoblieAddCityName.getRawValue()=='全部'){
		                		Ext.Msg.alert("信息!","请选择城市"); 
		                		return ;
		                	}
		                	
                    		var provinceIndex=areaMoblieAddProvinceName.selectedIndex<0?0:areaMoblieAddProvinceName.selectedIndex;
		                	var provinceStore=areaMoblieAddProvinceName.getStore();
		                	var provinceScode=provinceStore.data.items[provinceIndex].json.sCode;
		                	var cityScode='';
	                		var cityIndex=areaMoblieAddCityName.selectedIndex<0?0:areaMoblieAddCityName.selectedIndex;
		                	var cityStore=areaMoblieAddCityName.getStore();
		                	cityScode=cityStore.data.items[cityIndex].json.sCode;
                	
                    		Ext.Ajax.request({
								url:'addAreaMoblie.do',
								method:'POST',
								params : {
				                   smoblieNo:areaMoblieAddNameField.getValue(),
				                   sprovinceName:areaMoblieAddProvinceName.getRawValue(),
				                   sprovinceCode:provinceScode,
				                   nprovinceId:areaMoblieAddProvinceName.getValue(),
				                   scityName:areaMoblieAddCityName.getRawValue(),
				                   scityCode:cityScode,
				                   ncityId:areaMoblieAddCityName.getValue(),
				                   nop:areaMoblieAddnOPField.getValue()
				                }, 
				  				success: function (response) {
	
				  					if(response.responseText=='true'){
			                            Ext.MessageBox.alert('信息!', '添加成功!');
			                            areaMoblieAddform.getForm().reset();
			                            areaMoblieAddWin.hide();
			                            areaMoblieGridStore.reload();
				  					}
				  					else{
				  						Ext.Msg.alert("Error","添加信息失败！"); 
				  					}
				              	}, 
				  				failure: function (response) {
				                    Ext.Msg.alert("Error","错误"); 
				            	}
							});
                    	}else if(this.text=='修 改'){
                    		Ext.Ajax.request({
								url:'updateAreaMoblie.do',
								method:'POST',
								params : {
								   nmobileRelAreaId : areaMoblieId,
				                   smoblieNo:areaMoblieAddNameField.getValue(),
				                   nop:areaMoblieAddnOPField.getValue()
				                }, 
				  				success: function (response) {
	
				  					if(response.responseText=='true'){
			                            Ext.MessageBox.alert('信息!', '修改成功!');
			                            areaMoblieAddform.getForm().reset();
			                            areaMoblieAddWin.hide();
			                            areaMoblieGridStore.reload();
				  					}
				  					else{
				  						Ext.Msg.alert("Error","修改信息失败！"); 
				  					}
				              	}, 
				  				failure: function (response) {
				                    Ext.Msg.alert("Error","错误"); 
				            	}
							});
                    	}
                    	
                    	
                    }
                },{
                    text: '返 回',
                    handler: function() {
                    	areaMoblieAddform.getForm().reset();
                    	areaMoblieAddWin.hide();
                    }
                }]
            });

            areaMoblieAddWin =new Ext.Window({
                title: '添加手机号段',
                closeAction: 'hide',
                width: 320,
                height: 200,
                layout: 'fit',
                resizable: true,
                modal: true,
                items: areaMoblieAddform,
                listeners :{
	            	close:function(){
	            		areaMoblieAddWin.getForm().reset();
	            	}
            }
            });
        }
        areaMoblieAddWin.show();
        
        if(tinfo==2){
        	areaMoblieAddWin.setTitle('修改手机号段 标识：'+areaMoblieJson.nmobileRelAreaId);
    		areaMoblieAddform.buttons[0].setText('修 改');
    		
    		areaMoblieAddProvinceName.hide();
    		areaMoblieAddCityName.hide();
    		
            areaMoblieAddnOPField.setValue(areaMoblieJson.nop);
            areaMoblieAddNameField.setValue(areaMoblieJson.smoblieNo);
        }else{
        	areaMoblieAddProvinceName.show();
        	areaMoblieAddCityName.show();
        	areaMoblieAddform.getForm().reset();
        	areaMoblieAddWin.setTitle('添加手机号段 ');
    		areaMoblieAddform.buttons[0].setText('添 加');
        }
    }
    
function areaMoblieGridColumnsRenderUplink(nmobileRelAreaId){
	areaMoblieId=nmobileRelAreaId;
	
	if(nmobileRelAreaId){
		showareaMoblieAddForm(2,areaMoblieobj[nmobileRelAreaId]);
	}
}

function roleGridColumnsRenderDellink(mobileRelAreaId){
	
	Ext.MessageBox.confirm('信息', '是否确认删除手机号段 标识： '+mobileRelAreaId+'?', function(btn){
		
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'deleteAreaMoblie.do',
				method:'POST',
				params:{
					nmobileRelAreaId:mobileRelAreaId
				},
				success:function(response){
					if(response.responseText=='true'){
						Ext.MessageBox.alert('信息','删除成功！');
						areaMoblieGridStore.reload();
					}else{
						Ext.MessageBox.alert('ERROR','删除失败！');
					}
				},
				failure:function(){
					Ext.Msg.alert('ERROR','错误');
				}
			});
		}
	});
}